﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq.Expressions;
using System.Web;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using CamlexNET;
using LifeInSharePoint.Common;
using LifeInSharePoint.Common.Base;
using Microsoft.SharePoint;
using System.Web.UI.HtmlControls;

namespace LifeInSharePoint.Blog.Common.WebParts.LISPBlogAlbums
{
    [ToolboxItemAttribute(false)]
    public class LISPBlogAlbums : BaseWebPart
    {

        #region Private Properties

        private const string ALBUMSLIST = "Blog Gallery Albums";
        private const string CONTENTTYPE = "Life In SharePoint Blog Gallery Albums";
        private string transformedXML = null;
        private bool errorFound = false;
        private string errorMessage = null;
        private string photoAlbum = string.Empty;

        #endregion

        private string _XSLTPath = "/_layouts/LifeInSharePoint.Blog/xslt/Albums.xslt";
        [Personalizable(PersonalizationScope.Shared)]
        [WebBrowsable(true)]
        [System.ComponentModel.Category("Life In SharePoint")]
        [WebDisplayName("XSLT Path")]
        [WebDescription("Path the the XSLT")]
        public string XSLTPath
        {
            get { return _XSLTPath; }
            set { _XSLTPath = value; }
        }

        private string _RelSiteUrl = "/";
        [Personalizable(PersonalizationScope.Shared)]
        [WebBrowsable(true)]
        [System.ComponentModel.Category("Life In SharePoint")]
        [WebDisplayName("Rel Site Url")]
        [WebDescription("Rel Site Url")]
        public string RelSiteUrl
        {
            get { return _RelSiteUrl; }
            set { _RelSiteUrl = value; }
        }

        protected override void OnInit(EventArgs e)
        {
            this.ChromeType = PartChromeType.None;
            photoAlbum = SPQueryStringHelper.GetQueryStringItem(HttpContext.Current.Request.QueryString, "Album", String.Empty);
            this.ExportMode = WebPartExportMode.All;
            base.OnInit(e);
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            if (!string.IsNullOrEmpty(XSLTPath))
            {
                processData();
            }
            else
            {
                errorFound = true;
                errorMessage = "XSLT Path is not Defined - Please edit webpart Properties";
            }

        }

        protected override void CreateChildControls()
        {
            if (!errorFound)
            {
                HtmlGenericControl container = new HtmlGenericControl("Div");
                container.InnerHtml = transformedXML;
                this.Controls.Add(container);
            }
            else
            {
                Label errorMsg = new Label();
                errorMsg.Text = errorMessage;
                this.Controls.Add(errorMsg);
            }

        }

        private void processData()
        {
            //Get the SP Web
            SPWeb web = SPContext.Current.Site.RootWeb;

            //Get the List Instance
            SPList newslist = web.Lists[ALBUMSLIST];

            //Get a new SPQuery Instance
            SPQuery workQuery = new SPQuery();
            //Create Expressions for the CAMLEx
            var expressions = new List<Expression<Func<SPListItem, bool>>>();


            expressions.Add(x => ((string)x["ContentType"]) == CONTENTTYPE);
            var caml = Camlex.Query().WhereAny(expressions).ToString();

            workQuery.Query = caml + "<OrderBy><FieldRef Name='Modified' Ascending='False'/></OrderBy>";

            SPListItemCollection _workItemCollection = newslist.GetItems(workQuery);

            if (_workItemCollection != null && _workItemCollection.Count > 0)
            {
                DataTable AlbumDT = new DataTable("Album");
                AlbumDT.Columns.Add("ID");
                AlbumDT.Columns.Add("Title");
                AlbumDT.Columns.Add("PostCount");
                AlbumDT.Columns.Add("FilterLink");
                AlbumDT.Columns.Add("ClearFilterLink");

                foreach (SPListItem _workItem in _workItemCollection)
                {
                    string Title = SPListHelper.GetColumnStringValue(_workItem, "Title");
                    string ClearFilter = string.Empty;
                    if (!string.IsNullOrEmpty(photoAlbum))
                    {
                        if(photoAlbum == Title)
                        {
                            //Title matches the current filter

                            ClearFilter = "&nbsp;<a class='clearFilter' href='" + HttpContext.Current.Request.Path + "'> <img src='/_layouts/LifeInSharePoint.Blog/images/ClearFilter.gif' border='0' alt='Clear Filter' /> </a>";
                        }
                    }

                    int ID = SPListHelper.GetColumnIntValue(_workItem, "ID");
                    int Count = getAlbumPhotoCount(ID);
                    string FilterLink = "<a href='" + HttpContext.Current.Request.Path + "?Album=" + Title + "'>" +
                                        Title + "</a>";
                    if (Count > 0)
                    {
                        AlbumDT.Rows.Add(ID, Title, Count, FilterLink, ClearFilter);
                    }

                }
                if (AlbumDT.Rows.Count == 0)
                {
                    AlbumDT.Rows.Add(0, null,  null, "No Photos assigned to Albums");
                }

                DataSet AlbumDS = new DataSet("Albums");
                AlbumDS.Tables.Add(AlbumDT);
                string resultXML = AlbumDS.GetXml();
                transformedXML = SPWebPartHelper.ConvertXML(resultXML, SPContext.Current.Site.Url + XSLTPath);
            }
            else
            {
                DataTable AlbumDT = new DataTable("NoPhotos");
                AlbumDT.Columns.Add("Title");
                AlbumDT.Rows.Add("No Photos Found");
                DataSet AlbumDS = new DataSet("Albums");
                AlbumDS.Tables.Add(AlbumDT);
                string resultXML = AlbumDS.GetXml();
                transformedXML = SPWebPartHelper.ConvertXML(resultXML, SPContext.Current.Site.Url + XSLTPath);
            }


        }

        private int getAlbumPhotoCount(int AlbumID)
        {
            int postCount = 0;

            //Get the SP Web
            using (SPSite siteCollection = new SPSite(SPContext.Current.Site.RootWeb.Url + RelSiteUrl))
            {
                using (SPWeb web = siteCollection.OpenWeb())
                {
                    //Get the List Instance
                    SPList newslist = web.Lists["Blog Gallery"];

                    //Get a new SPQuery Instance
                    SPQuery workQuery = new SPQuery();

                    //Create Expressions for the CAMLEx
                    var expressions = new List<Expression<Func<SPListItem, bool>>>();
                    expressions.Add(x => x["LISPBlogGalleryAlbum"] == (DataTypes.LookupId)Convert.ToString(AlbumID));
                    var caml = Camlex.Query().WhereAll(expressions).ToString();
                    workQuery.Query = caml;

                    SPListItemCollection _workItemCollection = newslist.GetItems(workQuery);
                    if (_workItemCollection.Count > 0)
                    {
                        postCount = _workItemCollection.Count;
                    }
                }
            }

            return postCount;
        }
    }
}
